package suncertify.view.server;

import suncertify.util.Options;
import suncertify.util.Messages;
import suncertify.view.SwingUtils;
import suncertify.view.SCButton;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
 * Implementation of dialog with server-side options
 */
public class ServerOptionsDialog extends JDialog {
    private static final Messages msg = Messages.getInstance();
    private static final Options opts = Options.getInstance();
    private JTextField dbFile;
    private JButton saveButton;
    private JButton cancelButton;
    private JFrame parent;

    /**
     * contructor
     * @param parent parent frame
     */
    public ServerOptionsDialog(JFrame parent) {
        super(parent, msg.get("ui.server.options.title"), true);
        this.parent = parent;
        this.setResizable(false);
        JPanel pane = new JPanel();
        GridBagLayout gbl = new GridBagLayout();
        pane.setLayout(gbl);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.weightx = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridwidth = GridBagConstraints.RELATIVE;

        pane.add(new JLabel(msg.get("ui.server.options.label.db")), gbc);

        gbc.weightx = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        dbFile = new JTextField();
        pane.add(dbFile, gbc);

        gbc.fill = GridBagConstraints.NONE;
        saveButton = new SCButton(msg.get("ui.server.options.button.save"));
        saveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                opts.set(Options.REMOTE_DB_FILE, dbFile.getText());
                opts.save();
                setVisible(false);
            }
        });
        cancelButton = new SCButton(msg.get("ui.server.options.button.cancel"));
        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                setVisible(false);
            }
        });

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        pane.add(buttonPanel);

        gbc.weightx = 1;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        pane.add(buttonPanel, gbc);
        
        this.setContentPane(pane);
        this.pack();
        this.setSize(300, 120);
    }

    @Override
    public void setVisible(boolean value) {
        if (value) {
            dbFile.setText(opts.get(Options.REMOTE_DB_FILE));
            SwingUtils.placeCenter(this.parent, this);
        }
        super.setVisible(value);
    }
}
